package com.compass.mobile.ui.fragment

import UserInfoManager
import android.os.Bundle
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import com.compass.mobile.R
import com.compass.mobile.databinding.FragmentNewHomePageBinding
import com.compass.mobile.framework.base.BaseVBFragment
import com.compass.mobile.framework.constant.FOLLOW_ACTION
import com.compass.mobile.framework.constant.PATIENT_ID
import com.compass.mobile.framework.constant.REFRESH_PATIENT
import com.compass.mobile.framework.ext.onClick
import com.compass.mobile.framework.update.util.ApkUtil
import com.compass.mobile.framework.utils.FocusViewUtils
import com.compass.mobile.framework.utils.LiveDataBus
import com.compass.mobile.models.BannerData
import com.compass.mobile.models.PatientBean
import com.compass.mobile.ui.activity.ConvenientFunctionActivity
import com.compass.mobile.ui.activity.DepartmentFragmentActivity
import com.compass.mobile.ui.activity.FollowingPrescriptionActivity
import com.compass.mobile.ui.activity.HomePageActivity
import com.compass.mobile.ui.activity.IntelligentGuidanceActivity
import com.compass.mobile.ui.activity.PatientsActivity
import com.compass.mobile.ui.adapter.HosBannerAdapter
import com.compass.mobile.ui.dialog.AgreementDialog
import com.compass.mobile.ui.dialog.CommonMessageDialog
import com.compass.mobile.ui.viewModel.MainViewModel
import com.compass.mobile.ui.viewModel.UserViewModel
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.RequestCallback
import com.netease.nimlib.sdk.auth.AuthService
import com.netease.nimlib.sdk.auth.LoginInfo
import com.youth.banner.indicator.CircleIndicator
import getStringFromResource
import toJson

/**
 * Description： 新版首页
 * Date:2024/8/13 9:53
 */
class NewHomePageFragment : BaseVBFragment<FragmentNewHomePageBinding>() {
    private val mainViewModel: MainViewModel by activityViewModels()
    private val userViewModel: UserViewModel by viewModels()
    private var banners: ArrayList<BannerData> = ArrayList()
    override fun initView(view: View, savedInstanceState: Bundle?) {


        FocusViewUtils.scaleView(mBinding?.hosBanner, 0)
        FocusViewUtils.scaleView(mBinding?.llConvenientFunction, 1)
        FocusViewUtils.scaleView(mBinding?.llSwitchPatients, 1)
        FocusViewUtils.scaleView(mBinding?.llMail, 1)
        FocusViewUtils.scaleView(mBinding?.llInquiry, 1)
        FocusViewUtils.scaleView(mBinding?.llBookingRegister, 1)
        FocusViewUtils.scaleView(mBinding?.llChronicDisease, 1)
        FocusViewUtils.scaleView(mBinding?.tvPrivacyAgreement, 2)
        FocusViewUtils.scaleView(mBinding?.tvServiceAgreement, 2)
        initBanners()
        mBinding?.tvVersionName?.text="当前版本号：${ApkUtil.getVersionName(requireContext())}"
    }

    private fun initBanners() {
        banners.add(   
            BannerData(
                R.mipmap.icon_banner_def,
                "1"
            )
        )
//        banners.add(
//            BannerData(
//                R.mipmap.icon_banner01,
//                "2"
//            )
//        )

        mBinding?.hosBanner?.apply {
            addBannerLifecycleObserver(this@NewHomePageFragment)
            indicator = CircleIndicator(requireContext())


//            setIndicatorWidth(dpToPx(100),dpToPx(100))
//            setIndicatorNormalColor(getColorFromResource(R.color.white))
//            setIndicatorSelectedColor(getColorFromResource(R.color.dodgerblue))
//            setIndicatorSpace(dpToPx(20))
            setAdapter(HosBannerAdapter(banners, requireContext()))
            setLoopTime(4000)
            setOnClickListener {
                if (!UserInfoManager.isHaveDefPatient()) {
                    addPatientDialog()
                }else{
                    DepartmentFragmentActivity.start(requireContext(), "inquiry")
                }

            }
        }


    }

    override fun initData() {
        showLoading()
        mainViewModel.getDefPatient()
        mainViewModel.getAllDictionaries()
        userViewModel.gePatients()

        userViewModel.patientLiveData.observe(this) {
            it?.let { list ->
                UserInfoManager.savePatientList(list.toJson())
            }
            dismissLoading()
        }
        mainViewModel.patientDefLiveData.observe(this) {
            it?.let { bean ->
                UserInfoManager.savePatientInfo(bean.toJson())
                val homePageActivity = activity as HomePageActivity
                homePageActivity.setDefaultPatientView()
                doLoginIM(bean)
            } ?: kotlin.run {
                UserInfoManager.savePatientInfo(null)
                val homePageActivity = activity as HomePageActivity
                homePageActivity.setDefaultPatientView()
            }
        }

        LiveDataBus.get().with(FOLLOW_ACTION, String::class.java).observe(this) {
            mainViewModel.geRecommendDoctor()
        }
        //新增就诊人 删除就诊人
        LiveDataBus.get().with(REFRESH_PATIENT, String::class.java)
            .observe(this) {
                //退出当前登录的就诊人
                if (NIMClient.getCurrentAccount().isNullOrEmpty()) {
                    NIMClient.getService(AuthService::class.java).logout()
                }
                mainViewModel.getDefPatient()

            }


        mainViewModel.allDictionariesLiveData.observe(this) {
            it?.let { warp ->
                UserInfoManager.saveNotificationType(warp.patient_with_treatment_system_messages_type.toJson())
                UserInfoManager.saveOrderType(warp.order_consultation_status.toJson())
                UserInfoManager.saveOrderConsultationType(warp.order_consultation_type.toJson())
                UserInfoManager.saveInspectionReportType(warp.inspection_report_type.toJson())
                UserInfoManager.saveOrderNurseStatusType(warp.order_nurse_status.toJson())
                UserInfoManager.saveInspectionType(warp.order_inspection_status.toJson())
                UserInfoManager.saveSuggestType(warp.complaint_suggest_detail_type.toJson())
            }
        }
        mainViewModel.agreementLiveData.observe(this){ htmlDate->



            AgreementDialog.Builder(requireActivity(),agreementType, htmlDate)
                .setConfirm(getStringFromResource(R.string.default_confirm))
                .setCancel(getString(R.string.default_cancel))
                .setonCancelListener {
                    it?.dismiss()
                }
                .setonConfirmListener {
                    it?.dismiss()
                }.create().show()



        }


    }


    private fun addPatientDialog() {
        CommonMessageDialog.Builder(requireActivity())
            .setTitle("温馨提示")
            .setMessage("您还没有添加就诊人，是否去添加？")
            .setConfirm(getStringFromResource(R.string.default_confirm))
            .setCancel(getString(R.string.default_cancel))
            .setonCancelListener {
                it?.dismiss()
            }
            .setonConfirmListener {
                PatientsActivity.start(requireContext())
                it?.dismiss()
            }.create().show()
    }


    private var  agreementType:Int=0
    override fun intListener() {
        mBinding?.tvPrivacyAgreement?.onClick {
            agreementType=0
            mainViewModel.getHospitalConfig("content.serviceAgreement")


        }
        mBinding?.tvServiceAgreement?.onClick {
            agreementType=1
            mainViewModel.getHospitalConfig("content.privacyAgreement")

        }

        mBinding?.llConvenientFunction?.onClick {
            //便捷功能
            if (!UserInfoManager.isHaveDefPatient()) {
                addPatientDialog()
                return@onClick
            }
            ConvenientFunctionActivity.start(requireContext())
        }

        //就诊人管理
        mBinding?.llSwitchPatients?.onClick {
            PatientsActivity.start(requireContext())

        }
        //在线问诊
        mBinding?.llInquiry?.onClick {
            if (!UserInfoManager.isHaveDefPatient()) {
                addPatientDialog()
                return@onClick
            }
            DepartmentFragmentActivity.start(requireContext(), "inquiry")

        }
        //预约挂号
        mBinding?.llBookingRegister?.onClick {
            if (!UserInfoManager.isHaveDefPatient()) {
                addPatientDialog()
                return@onClick
            }
            DepartmentFragmentActivity.start(requireContext(), "booking")


        }

        //慢病管理
        mBinding?.llChronicDisease?.onClick {
            if (!UserInfoManager.isHaveDefPatient()) {
                addPatientDialog()
                return@onClick
            }

            FollowingPrescriptionActivity.start(requireContext())


        }
        mBinding?.llMail?.onClick {
            if (!UserInfoManager.isHaveDefPatient()) {
                addPatientDialog()
                return@onClick
            }
            IntelligentGuidanceActivity.start(requireContext())
        }

    }


    /**
     * 登录IM
     */
    private fun doLoginIM(patientBean: PatientBean) {
        val info = LoginInfo(patientBean.wyyxAccId, patientBean.wyyxToken)
        val callback: RequestCallback<LoginInfo?> = object : RequestCallback<LoginInfo?> {
            override fun onSuccess(param: LoginInfo?) {

                UserInfoManager.putString(PATIENT_ID,patientBean.id)

//                UserInfoManager.putString(PATIENT_ID,patientBean.id)
                UserInfoManager.saveImUserAccount(param?.account)
                UserInfoManager.saveImToken(param?.token)
//                showToast("就诊人登录成功")
            }

            override fun onFailed(code: Int) {


            }

            override fun onException(exception: Throwable) {

            }
        }
        //执行手动登录
        NIMClient.getService(AuthService::class.java).login(info).setCallback(callback)

    }

    override fun onStart() {
        super.onStart()
        mBinding?.hosBanner?.start()
    }

    override fun onStop() {
        super.onStop()
        mBinding?.hosBanner?.stop()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mBinding?.hosBanner?.destroy()
    }
}
